﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using SuperQuiz.Common;
using SuperQuiz.Logic;
using SuperQuiz.Model;
using SuperQuiz.View;
using TCD.Windows8.Controls;
using Windows.ApplicationModel.DataTransfer;
using Windows.ApplicationModel.Resources;
using Windows.Data.Xml.Dom;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

namespace SuperQuiz
{
    public sealed partial class QuizPlayPage : SuperQuiz.Common.LayoutAwarePage
    {
        public const bool CAMUFLATE_APPBAR = true;

        private DataTransferManager dataTransferManager;

        public QuizPlayPage()
        {
            this.InitializeComponent();
            QuizApplication.Instance.SetupSettingsEvents(this);
        }

        protected override async void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            this.dataTransferManager = DataTransferManager.GetForCurrentView();

            var questionNumber = 0;
            if (pageState != null && pageState.ContainsKey("QuizId"))
            {
                navigationParameter = pageState["QuizId"];
            }
            if (pageState != null && pageState.ContainsKey("QuestionNumber"))
            {
                questionNumber = (int)pageState["QuestionNumber"];
            }
            this.DefaultViewModel["QuizApplication"] = QuizApplication.Instance;

            await QuizApplication.Instance.AwaitLoad();
            var quizPlay = QuizApplication.Instance.GetQuizPlay((string)navigationParameter);
            this.DefaultViewModel["QuizPlay"] = quizPlay;
            quizPlay.OnEvaluateAnswer += quizPlay_OnEvaluateAnswer;
            UpdateSelectedAnswer();

            if (quizPlay.Quiz.AllowShareQuestions)
            {
                this.dataTransferManager.DataRequested += dataTransferManager_DataRequested;
            }

            SetupAppBar();
        }

        async void dataTransferManager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
        {
            DataPackage requestData = args.Request.Data;
            await QuizPlay.Share(requestData);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            this.dataTransferManager.DataRequested -= dataTransferManager_DataRequested;
        }

        void quizPlay_OnEvaluateAnswer(object sender, OnEvaluateAnswerEventArgs e)
        {
            var starPointsControl = new StarPointsControl(e.ScoredPoints);
            starsPlaceHolder.Children.Add(starPointsControl);
        }   

        protected override void SaveState(Dictionary<String, Object> pageState)
        {
            pageState["QuizId"] = QuizPlay.Quiz.UniqueId;
        }

        private void AnswerSelected(object sender, SelectionChangedEventArgs e)
        {
            var selectedAnswer = e.AddedItems.FirstOrDefault() as QuizAnswer;            
            var unselectedAnswer = e.RemovedItems.FirstOrDefault() as QuizAnswer;
            int? unselectedAnswerIndex = null;
            if (unselectedAnswer != null)
            {
                unselectedAnswerIndex = QuizPlay.CurrentQuestion.Answers.IndexOf(unselectedAnswer);
            }
            if (selectedAnswer != null || unselectedAnswerIndex.Equals(QuizPlay.CurrentAnswerIndex))
            {
                QuizPlay.CurrentAnswerIndex = QuizPlay.CurrentQuestion.Answers.IndexOf(selectedAnswer);
            }
        }

        private async void NextClick(object sender, RoutedEventArgs e)
        {
            if (await QuizPlay.Next())
            {
                UpdateSelectedAnswer();
                UpdateScrollPositions();
            }
        }

        private void UpdateScrollPositions()
        {
            questionDetailScrollViewer.ScrollToVerticalOffset(0);
            questionScrollViewer.ScrollToVerticalOffset(0);
        }

        private void ShareClick(object sender, RoutedEventArgs e)
        {
            ApplicationView.TryUnsnap();
            DataTransferManager.ShowShareUI();
        }

        private async void PreviousClick(object sender, RoutedEventArgs e)
        {
            if (await QuizPlay.Previous())
            {
                UpdateSelectedAnswer();
                UpdateScrollPositions();
            }
        }

        private async void FinishClick(object sender, RoutedEventArgs e)
        {
            await QuizPlay.Finish();

            if (!QuizPlay.Quiz.AllowShareQuestions)
            {
                this.dataTransferManager.DataRequested += dataTransferManager_DataRequested;
            }

            CreateTopAppBar();

            ShowResultsFlyout();
        }

        private void ShowResultsFlyout()
        {
            var resourceLoader = new ResourceLoader();

            Type resultsControlType = typeof(QuizResultsControl);
            if (!string.IsNullOrEmpty(QuizPlay.Quiz.ResultsControlFullName))
            {
                resultsControlType = Type.GetType(QuizPlay.Quiz.ResultsControlFullName);
            }
            FrameworkElement resultsControl = (FrameworkElement)Activator.CreateInstance(resultsControlType);
            resultsControl.DataContext = QuizPlay.Results;

            Flyout f = new Flyout(
                new SolidColorBrush(Colors.Black),
                new SolidColorBrush(Colors.BlanchedAlmond),
                resourceLoader.GetString("ResultsTitle"),
                (ApplicationViewStates.CurrentState != Snapped) ? FlyoutDimension.Wide : FlyoutDimension.Narrow,//switch between narrow and wide depending on the check box
                resultsControl);
            f.Show();
        }

        private async void ResultsClick(object sender, RoutedEventArgs e)
        {
            if (!QuizPlay.Quiz.LockQuestionWhenEvaluated)
            {
                await QuizPlay.Finish();
            }
            ShowResultsFlyout();
        }

        private void UpdateSelectedAnswer()
        {
            answersList.ItemsSource = QuizPlay.CurrentQuestion.Answers;
            answersList.SelectedIndex = QuizPlay.CurrentAnswerIndex;
        }

        public QuizPlay QuizPlay { get { return (QuizPlay)this.DefaultViewModel["QuizPlay"]; } }

        private void AppBarClosed(object sender, object e)
        {
            if (CAMUFLATE_APPBAR)
                BottomAppBar.IsOpen = true;
        }

        private void SetupAppBar()
        {
            CreateTopAppBar();
            if (CAMUFLATE_APPBAR)
            {
                BottomAppBar.BorderBrush = null;
                BottomAppBar.Background = null;
            }
        }

        private void CreateTopAppBar()
        {
            if (QuizPlay.Results == null || !QuizPlay.Quiz.ShowHomeButtonOnFinish)
                return;

            if (TopAppBar == null)
            {
                var resourceLoader = new ResourceLoader();

                var stackPanel = new StackPanel();
                stackPanel.Orientation = Orientation.Horizontal;

                var homeButton = new Button();
                Windows.UI.Xaml.Automation.AutomationProperties.SetName(homeButton, resourceLoader.GetString("Home"));
                homeButton.Style = App.Current.Resources["HomeAppBarButtonStyle"] as Style;
                homeButton.Click += (sender, e) => 
                { 
                    this.Frame.Navigate(typeof(HomePage), null); 
                };
                stackPanel.Children.Add(homeButton);

                TopAppBar = new AppBar();
                TopAppBar.Content = stackPanel;
            }
            TopAppBar.IsOpen = true;
        }
    }
}
